using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace DOTS.DOD.LESSON3
{
    [BurstCompile]
    [RequireMatchingQueriesForUpdate] //该 System 中每个 EntityQuery 的结果都是空时会强制跳过 OnUpdate
    [UpdateInGroup(typeof(CreateEntitiesByPrefabSystemGroup))]
    partial struct CubeGenerateByPrefabSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            //只有当 CubeGeneratorByPrefab 组件存在时，该 System 才运行
            state.RequireForUpdate<CubeGeneratorByPrefab>();
        }
        
        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var generator = SystemAPI.GetSingleton<CubeGeneratorByPrefab>();
            var cubes = CollectionHelper.CreateNativeArray<Entity>(generator.CubeCount, Allocator.Temp);
            state.EntityManager.Instantiate(generator.CubeEntityProtoType, cubes);
            int count = 0;
            foreach (var cube in cubes)
            {
                state.EntityManager.AddComponentData(cube, new RotateAndMoveSpeed()
                {
                    RotateSpeed = count * math.radians(60f),
                    MoveSpeed = count,
                });
                var position = new float3((count - generator.CubeCount * 0.5f) * 1.5f, 0, 0);
                var transform = SystemAPI.GetComponentRW<LocalTransform>(cube);
                transform.ValueRW.Position = position;
                count++;
            }

            cubes.Dispose();
            state.Enabled = false; //只运行一次
        }
    }
}